package com.mdd.maduoduo.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;

import androidx.core.app.ActivityCompat;

public class MuPermission {
    private final Activity mActivity;

    private OnPermissionListener mListener;


    public MuPermission(Activity activity) {
        this.mActivity = activity;
    }


    // 判断权限
    public boolean permissionOk(String permission){
        return (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(mActivity, permission));
    }

    // 判断多个权限
    public boolean permissionsOk(String[] permission){
        for (String s : permission) {
            if (!(PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(mActivity, s))){
                return false;
            }
        }
        return true;
    }


    // 申请权限
    public void requestPermission(String permission, int requestCode, OnPermissionListener listener) {
        if (listener==null) return;
        this.mListener = listener;
        if (permissionOk(permission)) {
            mListener.onPermissionGranted();
        } else {
            ActivityCompat.requestPermissions(mActivity, new String[]{permission}, requestCode);
        }
    }

    // 申请权限
    public void requestPermission(String[] permission, int requestCode, OnPermissionListener listener) {
        if (listener==null) return;
        this.mListener = listener;
        for (String s : permission) {
            if (permissionOk(s)) {
                mListener.onPermissionGranted();
            } else {
                ActivityCompat.requestPermissions(mActivity, permission, requestCode);
            }
        }

    }


    // 处理申请结果
    public void onRequestPermissionsResult(String permissions, int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mListener.onPermissionGranted();
        } else {
            mListener.onPermissionDenied();
        }
    }


    // 打开app的详细页面
    public void toAppDetail(int requestCode){
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
        intent.setData(uri);
        mActivity.startActivityForResult(intent, requestCode);
    }

}
